import React, { FC, useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Typography, Space, Form, Input, Button, message } from 'antd'
import { UserAddOutlined } from '@ant-design/icons'
import { Link } from 'react-router-dom'
import { REGISTER_PATHNAME, MANAGE_INDEX_PATHNAME } from '../router'
import { loginService } from '../services/user'
import styles from './Login.module.scss'
import { useRequest } from 'ahooks'
import { setToken } from '../utils/user-token'

const Login: FC = () => {
  const { Title } = Typography
  const nav = useNavigate()

  const [form] = Form.useForm()

  useEffect(() => {
    form.setFieldsValue({ username: '', password: '' })
  }, [])

  const { run } = useRequest(
    async value => {
      const { username, password } = value
      const data = await loginService(username, password)

      return data
    },
    {
      manual: true,
      onSuccess(res) {
        const { token } = res
        setToken(token)
        message.success('登录成功')
        nav(MANAGE_INDEX_PATHNAME)
      }
    }
  )

  function onFinish(value: any) {
    console.log(value)
    run(value)
  }

  return (
    <div className={styles.container}>
      <div>
        <Space>
          <Title level={2}>
            <UserAddOutlined />
          </Title>
          <Title level={2}>用户登录</Title>
        </Space>
      </div>
      <div>
        <Form labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} onFinish={onFinish} form={form}>
          <Form.Item
            label="用户名"
            name="username"
            rules={[
              { required: true, message: '请输入用户名' },
              { type: 'string', min: 5, max: 20, message: '5-20之间' },
              { pattern: /^\w+$/, message: '只能是字母数字下划线' }
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码' }]}
          >
            <Input.Password />
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 6, span: 16 }}>
            <Space>
              <Button type="primary" htmlType="submit">
                登录
              </Button>
              <Link to={REGISTER_PATHNAME}>去注册</Link>
            </Space>
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Login
